﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using DevExpress.Data;
using DevExpress.Utils.Menu;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid;
using ERP_RORZE_DLL.Product.DAO;
using ERP_RORZE_DLL.Product.database;
using ERP_RORZE_PERMISSION.Base;
using ERP_RORZE_PRODUCT.Product.MO;
using BaseDAO = ERP_RORZE_TOOL.DBAccess.BaseDAO;
using Utilities = ERP_RORZE_TOOL.Common.Utilities;

namespace ERP_RORZE_PRODUCT.Product.WTS
{
    public partial class ctrlMachineWTSDetail : DevExpress.XtraEditors.XtraUserControl
    {
        ClsWTSDAO clsWTSDAO = new ClsWTSDAO();
        DXPopupMenu menue;
        DataTable dt;
        DXPopupMenu menu;
        DXPopupMenu menuXtra;
        private int range = 2;
        //private GridColumn[] columns;
        Utilities.ItemGridColumn[] columns;
        // GridView view= new GridView();
        private int i = 0;
        private LogUtils log;
        private bool loaded;

        public ctrlMachineWTSDetail()
        {
            InitializeComponent();
            InitDateRangeMenu();
            InitPopupMenu();
            InitPopupMenuXtra();
            this.dropbtDateRange.DropDownControl = menu;
            dropbtExport.DropDownControl = menue;
            dropbtExtra.DropDownControl = menuXtra;
            this.dropbtDateRange.Text = "One Month";

            log = new LogUtils();

        }

        void Reload(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            //DataTable dtMain = new DataTable();
            //if (loaded)
            //{
            //    gridView1.Columns.Clear();

            //    foreach (Utilities.ItemGridColumn column in columns)
            //    {
            //        column.Column.VisibleIndex = column.VisibleIndex;
            //        gridView1.Columns.Add(column.Column);
            //    }
            //}

            dt = clsWTSDAO.GetAll(range);
            //dt = clsWTSDAO.GetAllMachineWTSDetail();
            gridControl1.DataSource = dt;
            //            gridView1.PopulateColumns();
            gridView1.BestFitColumns();
            //if (!loaded)
            //{
            //    columns = new Utilities.ItemGridColumn[gridView1.Columns.Count];
            //    foreach (GridColumn gridColumn in gridView1.Columns)
            //    {
            //        columns[i] = new Utilities.ItemGridColumn();
            //        columns[i].VisibleIndex = gridColumn.VisibleIndex;
            //        columns[i].Column = gridColumn;
            //        i++;
            //    }
            //    loaded = true;
            //}
            Cursor.Current = Cursors.Default;

        }

        private void ctrlMachineWTSDetail_Load(object sender, EventArgs e)
        {
            Reload(sender, e);
        }

        private void btnAddNew_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            frm_MachineWTSAdd frmAdd = new frm_MachineWTSAdd();
            //frm_MachineWTSInput frmAdd = new frm_MachineWTSInput();
            frmAdd.Reload += new EventHandler(Reload);
            frmAdd.Show();
            Cursor.Current = Cursors.Default;
        }

        private void btEdit_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            //frm_MachineWTSEdit frmEdit = new frm_MachineWTSEdit();
            frm_MachineWTSUpdate frmEdit = new frm_MachineWTSUpdate();
            frmEdit.ID = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "ID").ToString();
            frmEdit.Shift = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "Shift").ToString();
            frmEdit.ClampTime = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "ClampTime").ToString();
            frmEdit.Date = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "Date").ToString();
            frmEdit.MachineID = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "MachineID").ToString();
            frmEdit.MONo = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "MONo").ToString();
            frmEdit.NGQty = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "NGQty").ToString();
            frmEdit.Note1 = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "Note1").ToString();
            frmEdit.Note2 = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "Note2").ToString();
            frmEdit.OKQty = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "OKQty").ToString();
            frmEdit.OptionID = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "OptionID").ToString();
            frmEdit.ProTime = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "ProTime").ToString();
            frmEdit.StaffID = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "StaffID").ToString();
            frmEdit.Time = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "Time").ToString();
            frmEdit.WorkID = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "WorkID").ToString();

            frmEdit.Reload += new EventHandler(Reload);
            frmEdit.Show();
            Cursor.Current = Cursors.Default;
        }

        private void btnBusOderCancel_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            frm_MachineWTSFind frmFind = new frm_MachineWTSFind(this);
            frmFind.Show();
            Cursor.Current = Cursors.Default;
        }

        private void btnWTStoGA_Click(object sender, EventArgs e)
        {
            frm_MachineWTStoGA frmToGA = new frm_MachineWTStoGA();
            frmToGA.Show();
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            Reload(sender, e);
        }

        private void btReload_Click(object sender, EventArgs e)
        {
            Reload(sender, e);
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            btnAddNew_Click(sender, e);
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            btEdit_Click(sender, e);
        }

        private void btnDelete_Click(object sender, EventArgs e){
            //if (MessageBox.Show("Bạn có thực sự muốn xóa dữ liệu!", "Message", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            //{
            //    ClsMachineWTSTable b = new ClsMachineWTSTable();
            //    b.ID = int.Parse(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "ID").ToString());
            //    clsWTSDAO.DeleteMachineWTS(b);
            //    Reload(sender, e);
            //}

            if (gridView1.SelectedRowsCount > 0)
            {
                ClsMachineWTSTable b = new ClsMachineWTSTable();
                var row = new DataRow[gridView1.SelectedRowsCount];
                var laborId = new string[gridView1.SelectedRowsCount];

                for (int i = 0; i < gridView1.SelectedRowsCount; i++)
                {
                    row[i] = gridView1.GetDataRow(gridView1.GetSelectedRows()[i]);
                    laborId[i] = row[i]["ID"].ToString();
                }


                if (MessageBox.Show("Bạn có thực sự muốn xóa dữ liệu!", "Message", MessageBoxButtons.OKCancel,
                                MessageBoxIcon.Question) == DialogResult.OK)
                {
                    try
                    {
                        for (int i = 0; i < laborId.Length; i++)
                        {

                            b.ID = int.Parse(laborId[i]);
                            clsWTSDAO.DeleteMachineWTS(b);

                            //write Log
                            log.Table = LogConstant.Table.Product.MachineWTS;
                            log.Task = LogConstant.Task.Delete;
                            log.Description = "Date: " + row[i]["Date"] + "; MONo: " + row[i]["MONo"] + "; MachineID: " + row[i]["MachineID"] + "; OptionID: " + row[i]["OptionID"] + "; Shift: " + row[i]["Shift"] + "; WorkID: " + row[i]["WorkID"] + "; Time: " + row[i]["Time"] + "; ProTime: " + row[i]["ProTime"] + "; ClampTime: " + row[i]["ClampTime"];
                            log.WriteLog();

                        }
                        MessageBox.Show("Đã xóa!");

                    }
                    catch (Exception ex)
                    {

                        MessageBox.Show("Error: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                    }

                }
            }
        }

        private void btDelete_Click(object sender, EventArgs e)
        {
            btnDelete_Click(sender, e);
        }

        private void btnMOStart_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            ctrlMOStart frmMOStart = new ctrlMOStart();
            frmMOStart.Text = "MO Start";
            frmMOStart.Reload += new EventHandler(Reload);
            frmMOStart.Show();
            Cursor.Current = Cursors.Default;
        }

        //Date range
        protected virtual void InitDateRangeMenu()
        {
            menu = new DXPopupMenu();
            menu.Items.Add(new DXMenuItem("One Week", new EventHandler(OnItemClick1Week), null, null, null, null));
            menu.Items.Add(new DXMenuItem("One Month", new EventHandler(OnItemClick1Month), null, null, null, null));
            menu.Items.Add(new DXMenuItem("6 Months", new EventHandler(OnItemClick6Months), null, null, null, null));
            menu.Items.Add(new DXMenuItem("One Year", new EventHandler(OnItemClick1Year), null, null, null, null));
            menu.Items.Add(new DXMenuItem("All time", new EventHandler(OnItemClickAllTime), null, null, null, null));

        }

        void OnItemClick1Week(object sender, EventArgs e)
        {
            BindDatatoGrid(1);
            range = 1;
            dropbtDateRange.Text = "One Week";
        }

        void OnItemClick1Month(object sender, EventArgs e)
        {
            BindDatatoGrid(2);
            range = 2;
            dropbtDateRange.Text = "One Month";
        }

        void OnItemClick6Months(object sender, EventArgs e)
        {
            BindDatatoGrid(3);
            range = 3;
            dropbtDateRange.Text = "6 Months";
        }

        void OnItemClick1Year(object sender, EventArgs e)
        {
            BindDatatoGrid(4);
            range = 4;
            dropbtDateRange.Text = "One Year";
        }

        void OnItemClickAllTime(object sender, EventArgs e)
        {
            BindDatatoGrid(0);
            range = 0;
            dropbtDateRange.Text = "All time";
        }

        private void BindDatatoGrid(int range)
        {
            Cursor.Current = Cursors.WaitCursor;

            //DataTable dtMain = new DataTable();
            //gridView1.Columns.Clear();

            //foreach (Utilities.ItemGridColumn column in columns)
            //{
            //    column.Column.VisibleIndex = column.VisibleIndex;
            //    gridView1.Columns.Add(column.Column);
            //}
            dt = clsWTSDAO.GetAll(range);
            gridControl1.DataSource = dt;
            //gridView1.PopulateColumns();
            gridView1.BestFitColumns();
            Cursor.Current = Cursors.Default;

        }
        
        public void BindDatatoGridFind(DataTable dtFind)
        {
            gridControl1.DataSource = dtFind;
            gridView1.BestFitColumns();
        }

        //Export to excel button
        protected virtual void InitPopupMenu()
        {
            menue = new DXPopupMenu();
            menue.Items.Add(new DXMenuItem("Export all", new EventHandler(OnItemClickExportAll), null, null, null, null));
            menue.Items.Add(new DXMenuItem("Export selected row(s)", new EventHandler(OnItemClickExportRows), null, null, null, null));

        }
        void OnItemClickExportAll(object sender, EventArgs e)
        {
            // gridView1.
            Utilities.ExportToExcel(gridView1, 1, true);
        }
        void OnItemClickExportRows(object sender, EventArgs e)
        {
            Utilities.ExportToExcel(gridView1, 0, true);
        }

        //Extra functions
        protected virtual void InitPopupMenuXtra()
        {
            menuXtra = new DXPopupMenu();
            menuXtra.Items.Add(new DXMenuItem("Check Staff Time", new EventHandler(OnItemClickCheckTGNV), null, null, null, null));

        }
        void OnItemClickCheckTGNV(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            frm_CheckStaffTime frmCheck = new frm_CheckStaffTime(this.range);
            frmCheck.StartPosition = FormStartPosition.CenterScreen;
            frmCheck.Show();
            Cursor.Current = Cursors.Default;
        }

        public void Search(string where)
        {
            DataTable dt1 = new DataTable();
            dt1 = clsWTSDAO.SearchMachineWTS(where);
            gridControl1.DataSource = dt1;
            gridView1.PopulateColumns();
            gridView1.BestFitColumns();
        }

        private void gridView1_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            GridView view = sender as GridView;


            //Kiểm tra đây là dòng dữ liệu mới hay cũ, nếu là mới thì mình insert
            if (view.IsNewItemRow(e.RowHandle))
            {
                //e.RowHandle trả về giá trị int là thứ tự của dòng hiện tại

            }
            //Cũ thì update
            else
            {
                string temDate = (view.GetRowCellValue(e.RowHandle, view.Columns["Date"]).ToString().Trim() != string.Empty) ? DateTime.Parse(view.GetRowCellValue(e.RowHandle, view.Columns["Date"]).ToString()).ToString("yyyy/MM/dd") : view.GetRowCellValue(e.RowHandle, view.Columns["Date"]).ToString().Trim();

                string date = (temDate == "0001/01/01") ? "null" : "'" + DateTime.Parse(view.GetRowCellValue(e.RowHandle, view.Columns["Date"]).ToString()).ToString("yyyy/MM/dd") + "'";

                //string tem = view.GetRowCellValue(e.RowHandle, view.Columns["SProTime"]).ToString();

                //string date = (view.GetRowCellValue(e.RowHandle, view.Columns["Date"]).ToString() == "") ? "null" : "'" + view.GetRowCellValue(e.RowHandle, view.Columns["Date"]).ToString() + "'";
                string shift = (view.GetRowCellValue(e.RowHandle, view.Columns["Shift"]).ToString() == "") ? "null" : "N'" + view.GetRowCellValue(e.RowHandle, view.Columns["Shift"]).ToString() + "'";
                string staffID = (view.GetRowCellValue(e.RowHandle, view.Columns["StaffID"]).ToString() == "") ? "null" : "N'" + view.GetRowCellValue(e.RowHandle, view.Columns["StaffID"]).ToString() + "'";
                string machineID = (view.GetRowCellValue(e.RowHandle, view.Columns["MachineID"]).ToString() == "") ? "null" : "N'" + view.GetRowCellValue(e.RowHandle, view.Columns["MachineID"]).ToString() + "'";
                string mONo = (view.GetRowCellValue(e.RowHandle, view.Columns["MONo"]).ToString() == "") ? "null" : "N'" + view.GetRowCellValue(e.RowHandle, view.Columns["MONo"]).ToString() + "'";
                string optionID = (view.GetRowCellValue(e.RowHandle, view.Columns["OptionID"]).ToString() == "") ? "null" : "N'" + view.GetRowCellValue(e.RowHandle, view.Columns["OptionID"]).ToString() + "'";
                string workID = (view.GetRowCellValue(e.RowHandle, view.Columns["WorkID"]).ToString() == "") ? "null" : "N'" + view.GetRowCellValue(e.RowHandle, view.Columns["WorkID"]).ToString() + "'";
                string time = (view.GetRowCellValue(e.RowHandle, view.Columns["Time"]).ToString() == "") ? "null" : view.GetRowCellValue(e.RowHandle, view.Columns["Time"]).ToString();
                string oKQty = (view.GetRowCellValue(e.RowHandle, view.Columns["OKQty"]).ToString() == "") ? "null" : view.GetRowCellValue(e.RowHandle, view.Columns["OKQty"]).ToString();
                string nGQty = (view.GetRowCellValue(e.RowHandle, view.Columns["NGQty"]).ToString() == "") ? "null" : view.GetRowCellValue(e.RowHandle, view.Columns["NGQty"]).ToString();
                string proTime = (view.GetRowCellValue(e.RowHandle, view.Columns["ProTime"]).ToString() == "") ? "null" : view.GetRowCellValue(e.RowHandle, view.Columns["ProTime"]).ToString();
                string clamptime = (view.GetRowCellValue(e.RowHandle, view.Columns["ClampTime"]).ToString() == "") ? "null" : view.GetRowCellValue(e.RowHandle, view.Columns["ClampTime"]).ToString();
                string note1 = (view.GetRowCellValue(e.RowHandle, view.Columns["Note1"]).ToString() == "") ? "null" : "N'" + view.GetRowCellValue(e.RowHandle, view.Columns["Note1"]).ToString() + "'";
                string note2 = (view.GetRowCellValue(e.RowHandle, view.Columns["Note2"]).ToString() == "") ? "null" : "N'" + view.GetRowCellValue(e.RowHandle, view.Columns["Note2"]).ToString() + "'";
                string from = (view.GetRowCellValue(e.RowHandle, view.Columns["From"]).ToString() == "") ? "null" : "N'" + view.GetRowCellValue(e.RowHandle, view.Columns["From"]).ToString() + "'";
                string to = (view.GetRowCellValue(e.RowHandle, view.Columns["to"]).ToString() == "") ? "null" : "N'" + view.GetRowCellValue(e.RowHandle, view.Columns["to"]).ToString() + "'";
                string sProTime = (view.GetRowCellValue(e.RowHandle, view.Columns["SProTime"]).ToString() == string.Empty) ? "null" : view.GetRowCellValue(e.RowHandle, view.Columns["SProTime"]).ToString();
                string sClampTime = (view.GetRowCellValue(e.RowHandle, view.Columns["SClampTime"]).ToString() == "") ? "null" : view.GetRowCellValue(e.RowHandle, view.Columns["SClampTime"]).ToString();
                string tOKQty = (view.GetRowCellValue(e.RowHandle, view.Columns["TOKQty"]).ToString() == "") ? "null" : view.GetRowCellValue(e.RowHandle, view.Columns["TOKQty"]).ToString();
                string tNGQty = (view.GetRowCellValue(e.RowHandle, view.Columns["TNGQty"]).ToString() == "") ? "null" : view.GetRowCellValue(e.RowHandle, view.Columns["TNGQty"]).ToString();
                string id = (view.GetRowCellValue(e.RowHandle, view.Columns["ID"]).ToString() == "") ? "null" : view.GetRowCellValue(e.RowHandle, view.Columns["ID"]).ToString();

                string update = "update [242_MachineWTS] set [date]=" + date
                    + ", Shift = " + shift
                    + ", StaffID = " + staffID
                    + ", [MachineID] = " + machineID
                    + ", [MONo] = " + mONo
                    + ", [OptionID] = " + optionID
                    + ", [WorkID] = " + workID
                    + ", [time] = " + time
                    + ", [OKQty] = " + oKQty
                    + ", [NGQty] = " + nGQty
                    + ", [ProTime] = " + proTime
                    + ", [Clamptime] = " + clamptime
                    + ", [Note1] = " + note1
                    + ", [Note2] = " + note2
                    + ", [From] = " + from
                    + ", [To] = " + to
                    + ", [SProTime] = " + sProTime
                    + ", [SClampTime] = " + sClampTime
                    + ", [TOKQty] = " + tOKQty
                    + ", [TNGQty] = " + tNGQty
                    + " where [ID] = " + id;
                if (BaseDAO.ExecuteNonQuery(update) > 0)
                {

                    //write Log
                    log.Table = LogConstant.Table.Product.MachineWTS;
                    log.Task = LogConstant.Task.Update;
                    log.Description = "Date: " + date + "; MONo: " + mONo + "; MachineID: " + machineID + "; OptionID: "
                                + optionID + "; Shift: " + shift + "; WorkID: " + workID + "; Time: " + time
                                + "; ProTime: " + proTime + "; ClampTime: " + clamptime;
                    log.WriteLog();

                }

            }
        }

        private void gridView1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Alt)
            {
                if (e.KeyCode == Keys.E)
                {
                    if (gridView1.OptionsBehavior.Editable)
                    {
                        //gridView1.fo;
                        gridView1.OptionsBehavior.Editable = false;
                    }
                    else
                    {
                        gridView1.OptionsBehavior.Editable = true;
                        gridView1.Columns["ID"].OptionsColumn.AllowEdit = false;
                    }
                }
            }
        }
    }
}
